<template>
  <div class="page-box" style="position: relative;">
    <el-form ref="formGeneralUnitBasicRef" :size="layoutStore.defaultFormItemSize" label-width="120px"
      label-position="right" @submit.prevent>
      <filter-box :item-width="350" @search="refreshFormGeneralUnitBasic()" @reset="resetFormGeneralUnitBasic">
        <el-form-item label="单位名称">
          <el-input class="filter-item" v-model="formFilter.dwmcFilter" type="text" placeholder="" :clearable="true"
            :show-word-limit="false" maxlength="" />
        </el-form-item>
        <el-form-item label="单位类别">
          <el-select class="input-item" v-model="formFilter.dwlbmFilter" placeholder="" :clearable="true"
            :filterable="true">
            <el-option v-for="item in UnitCategoryList" :key="item.id" :label="item.name" :value="item.itemId" />
          </el-select>

        </el-form-item>
        <el-form-item label="单位办别">

          <el-select class="input-item" v-model="formFilter.dwbbmFilter" placeholder="" :clearable="true"
            :filterable="true">
            <el-option v-for="item in UnitFoundList" :key="item.id" :label="item.name" :value="item.itemId" />
          </el-select>

        </el-form-item>
        <el-form-item label="机构类别">

          <el-select class="input-item" v-model="formFilter.jglbmFilter" placeholder="" :clearable="true"
            :filterable="true">
            <el-option v-for="item in InstitutionTypeList" :key="item.id" :label="item.name" :value="item.itemId" />
          </el-select>

        </el-form-item>
      </filter-box>
    </el-form>
    <table-box ref="formGeneralUnitBasicTable" class="page-table" :data="formGeneralUnitBasicTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize" :row-config="{ isCurrent: false, isHover: true }"
      :seq-config="{ startIndex: ((formGeneralUnitBasicTableWidgetCurrentPage - 1) * formGeneralUnitBasicTableWidgetPageSize) }"
      :sort-config="{ remote: true }" :hasExtend="true" @sort-change="formGeneralUnitBasicTableWidget.onSortChange"
      @refresh="formGeneralUnitBasicTableWidget.refreshTable()">
      <template #operator>
        <el-button type="primary" :size="layoutStore.defaultFormItemSize" @click="onAddGeneralUnitBasicClick()">
          新建
        </el-button>
      </template>
      <vxe-column title="序号" type="seq" fixed="left" :index="formGeneralUnitBasicTableWidget.getTableIndex"
        :width="80" />
      <vxe-column title="单位号" field="dwh" />
      <vxe-column title="单位名称" field="dwmc" />
      <vxe-column title="单位简称" field="dwjc" />
      <vxe-column title="单位地址" field="dwdz" />
      <vxe-column title="单位类别" field="dwlbmDictMap.name" />
      <vxe-column title="单位办别" field="dwbbm" />
      <vxe-column title="是否实体" field="sfst" />
      <vxe-column title="建立年月" field="jlny">
        <template v-slot="scope">
          <span>{{ formatDateByStatsType(scope.row.jlny, 'day') }}</span>
        </template>
      </vxe-column>
      <vxe-column title="机构类别" field="jglbm" />
      <vxe-column title="更新时间" field="updateTime">
        <template v-slot="scope">
          <span>{{ formatDateByStatsType(scope.row.updateTime, 'day') }}</span>
        </template>
      </vxe-column>
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button link type="primary" :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditGeneralUnitBasicClick(scope.row)">
            编辑
          </el-button>
          <el-button link type="primary" :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteGeneralUnitBasicClick(scope.row)">
            删除
          </el-button>
        </template>
      </vxe-column>
      <template slot="empty">
        <div class="table-empty unified-font">
          <img src="@/assets/img/empty.png">
          <span>暂无数据</span>
        </div>
      </template>
      <!-- 分页 -->
      <template #pagination>
        <el-row type="flex" justify="end" style="margin-top: 10px;">
          <el-pagination :total="formGeneralUnitBasicTableWidgetTotalCount"
            :current-page="formGeneralUnitBasicTableWidgetCurrentPage"
            :page-size="formGeneralUnitBasicTableWidgetPageSize" :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formGeneralUnitBasicTableWidget.onCurrentPageChange"
            @size-change="formGeneralUnitBasicTableWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
    <label v-if="subPage" class="page-close-box" @click="onCancel()">
      <img src="@/assets/img/back2.png" alt="">
    </label>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formGeneralUnitBasic',
};
</script>

<script setup lang="ts">
import * as validateRules from '@/common/utils/validate';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { GeneralUnitBasicData } from '@/api/generated/generalUnitBasicController';
import { GeneralUnitBasicController } from '@/api/generated';
import { SysGlobalDictController } from '@/api/system';
import FormEditGeneralUnitBasic from '@/pages/UnitBasic/formEditGeneralUnitBasic.vue';
import DeptSelect from '@/components/DeptSelect/index.vue';
import UserSelect from '@/components/UserSelect/index.vue';

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const {
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
  }>(),
  {
    subPage: 0,
  },
);

const formFilter = reactive({
  // 单位名称
  dwmcFilter: undefined,
  // 单位类别码
  dwlbmFilter: undefined,
  // 单位办别码
  dwbbmFilter: undefined,
  // 机构类别码
  jglbmFilter: undefined,
});
const formFilterCopy = reactive({
  // 单位名称
  dwmcFilter: undefined,
  // 单位类别码
  dwlbmFilter: undefined,
  // 单位办别码
  dwbbmFilter: undefined,
  // 机构类别码
  jglbmFilter: undefined,
});
const instance = getCurrentInstance();

const onCancel = () => {
  router.go(-1);
  layoutStore.removeCachePage(route.fullPath as string);
  route.meta.refreshParentCachedPage = true;
};

const onResume = () => {
  refreshFormGeneralUnitBasic();
};

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormGeneralUnitBasicTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    generalUnitBasicDtoFilter: {
      dwmc: formFilter.dwmcFilter,
      dwlbm: formFilter.dwlbmFilter,
      dwbbm: formFilter.dwbbmFilter,
      jglbm: formFilter.jglbmFilter,
    }
  };
  return new Promise((resolve, reject) => {
    GeneralUnitBasicController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormGeneralUnitBasicTableVerify = () => {
  formFilterCopy.dwmcFilter = formFilter.dwmcFilter;
  formFilterCopy.dwlbmFilter = formFilter.dwlbmFilter;
  formFilterCopy.dwbbmFilter = formFilter.dwbbmFilter;
  formFilterCopy.jglbmFilter = formFilter.jglbmFilter;
  return true;
};
/**
 * 新建
 */
const onAddGeneralUnitBasicClick = (row?: GeneralUnitBasicData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建', FormEditGeneralUnitBasic, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formGeneralUnitBasicTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 编辑
 */
const onEditGeneralUnitBasicClick = (row?: GeneralUnitBasicData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  Dialog
    .show('编辑', FormEditGeneralUnitBasic, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formGeneralUnitBasicTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 删除
 */
const onDeleteGeneralUnitBasicClick = (row?: GeneralUnitBasicData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    GeneralUnitBasicController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formGeneralUnitBasicTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formGeneralUnitBasicTableOptions: TableOptions<GeneralUnitBasicData> = {
  loadTableData: loadFormGeneralUnitBasicTableWidgetData,
  verifyTableParameter: loadFormGeneralUnitBasicTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formGeneralUnitBasicTable = ref();
const formGeneralUnitBasicTableWidget = useTable(formGeneralUnitBasicTableOptions);
const {
  dataList: formGeneralUnitBasicTableWidgetDataList,
  currentPage: formGeneralUnitBasicTableWidgetCurrentPage,
  pageSize: formGeneralUnitBasicTableWidgetPageSize,
  totalCount: formGeneralUnitBasicTableWidgetTotalCount,
} = formGeneralUnitBasicTableWidget;
const refreshFormGeneralUnitBasic = () => {
  // 刷新段落
  formGeneralUnitBasicTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormGeneralUnitBasic = () => {
  formFilter.dwmcFilter = undefined;
  formFilterCopy.dwmcFilter = undefined;
  formFilter.dwlbmFilter = undefined;
  formFilterCopy.dwlbmFilter = undefined;
  formFilter.dwbbmFilter = undefined;
  formFilterCopy.dwbbmFilter = undefined;
  formFilter.jglbmFilter = undefined;
  formFilterCopy.jglbmFilter = undefined;
  refreshFormGeneralUnitBasic();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormGeneralUnitBasic();
};
const formInit = () => {
  initDictByCodeUnitCategory();
  initDictByCodeUnitFound();
  initDictByCodeInstitutionType();
  refreshFormGeneralUnitBasic();
};

const UnitCategoryList = ref([]) as any
async function initDictByCodeUnitCategory() {
  var params = {
    dictCode: "UnitCategory"
  }
  let res = await SysGlobalDictController.listAll(params);
  UnitCategoryList.value = res.data.fullResultList
}

const UnitFoundList = ref([]) as any
async function initDictByCodeUnitFound() {
  var params = {
    dictCode: "UnitFound"
  }
  let res = await SysGlobalDictController.listAll(params);
  UnitFoundList.value = res.data.fullResultList
}

const InstitutionTypeList = ref([]) as any
async function initDictByCodeInstitutionType() {
  var params = {
    dictCode: "InstitutionType"
  }
  let res = await SysGlobalDictController.listAll(params);
  InstitutionTypeList.value = res.data.fullResultList
}

onMounted(() => {
  formInit();
});

onActivated(() => {
  onResume();
});
</script>